<template>
	<view class="login"><button @getuserinfo="getUserInfo" open-type="getUserInfo" type="primary">授权微信登录</button></view>
</template>

<script>
export default {
	data() {
		return {};
	},
	methods: {
		async getUserInfo(e) {
			// 把用户信息储存到本地 到个人中心页要使用到
			  // console.log(e)
			    // 记录用户信息到本地缓存
			    uni.setStorage({
			        key: 'userInfo',
			        data: e.detail.userInfo
			    })
			    // 获取加密数据
			    const { encryptedData, iv, rawData, signature } = e.detail;
			    // 获取code属性，通过登录接口获取
			    const [error, res] = await uni.login()
			    const { code } = res;
			    // 发送网络请求登录
			    const [LoginError, loginRes] = await uni.request({
			        url: 'https://api-hmugo-web.itheima.net/api/public/v1/users/wxlogin',
			        method: 'POST',
			        data: {
			            encryptedData, iv, rawData, signature, code
			        }
			    })
				// 如果登录成功就把token值储存到本地
				if(loginRes.data.meta.status === 200){
					uni.setStorage({
						key:'token',
						data: loginRes.data.message.token
					})
					// 提示用户
					uni.showToast({
						title:'登录成功',
						icon:'none'
					})
					uni.navigateBack({
						data:1
					});
				}else{
					uni.showToast({
						title:'服务器异常,请重试',
						icon:'none'
					})
				}
		}
	}
};
</script>

<style lang="less">
.login {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	button {
		width: 461rpx;
		height: 88rpx;
		font-size: 36rpx;
		background-color: #07c160;
		color: #fff;
	}
}
</style>
